import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import request from '@/utils/axios';
//get请求
export const get = createAsyncThunk('counter/get', async (amount, thunkAPI) => {
  const { url, params = {}, isVerified = true } = amount;
  const { data } = await request.get(url, {
    params,
    headers: {
      Authorization: isVerified ? thunkAPI.getState().counter.token : null,
    },
  });
  return data;
});
//post请求
export const post = createAsyncThunk('counter/post', async (amount, thunkAPI) => {
  const { url, body = null, params = {}, isVerified = true } = amount;
  const { data } = await request.post(url, body, {
    params,
    headers: {
      Authorization: isVerified ? thunkAPI.getState().counter.userInfo.token : null,
    },
  });
  console.log(data);

  return data;
});

export const counterSlice = createSlice({
  name: 'counter',
  initialState: {
    value: 0,
    userInfo: {
      token: '',
      user_name: '',
      permissionCode: [], //路由权限码
    },
  },
  reducers: {
    increment: (state, { payload }) => {
      //这里直接修改即可
      state.value += payload.value;
    },
    decrement: (state) => {
      state.value -= 1;
    },
    setUserInfo: (state, { payload }) => {
      Object.assign(state.userInfo, payload);
    },
  },
  // extraReducers: (builder) => {
  //   builder
  //     .addCase(incrementAsync.pending, (state, action) => {
  //       console.log('异步操作进行中...', action);
  //     })
  //     .addCase(incrementAsync.fulfilled, (state, action) => {
  //       // state.value += action.payload;
  //       console.log('异步操作处理完成...', action, state);
  //     })
  //     .addCase(incrementAsync.rejected, (state, action) => {
  //       // 可以在这里添加错误处理逻辑
  //       console.error('异步操作失败:', action.error);
  //     });
  // },
});

// 为每个 case reducer 函数生成 Action creators
export const { increment, decrement, setUserInfo } = counterSlice.actions;

export default counterSlice.reducer;
